package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.CheckBox;
import com.cy.pj.sys.dao.SysRoleDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.pojo.SysRole;
import com.cy.pj.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色业务对象
 */
@Transactional(rollbackFor = Throwable.class,
        isolation = Isolation.READ_COMMITTED,
        timeout = 60)
@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;
    @Transactional(readOnly = true)
    @Override
    public List<SysRole> findRoles(SysRole sysRole) {
        return sysRoleDao.selectRoles(sysRole);
    }
    @Transactional(readOnly = true)
    @Override
    public SysRole findById(Integer id) {
        //多表关联查询
        return sysRoleDao.selectById(id);
        //单表多次查询
//      SysRole sysRole=sysRoleDao.selectById(id);//select * from sys_roles where id=#{id}
//      List<Integer> menuIds=sysRoleMenuDao.selectMenuIdsByRoleId(id);//select menu_id from sys_role_menus where role_id=#{id}
//      sysRole.setMenuIds(menuIds);
//      return sysRole;
    }

    @Override
    public int saveRole(SysRole sysRole) {
        //新增角色自身信息
        int rows=sysRoleDao.insertRole(sysRole);
        //新增角色菜单关系数据
        sysRoleMenuDao.insertRoleMenus(sysRole.getId(),sysRole.getMenuIds());
        throw new ServiceException("save error");
        // return rows;
    }
    @Override
    public int updateRole(SysRole sysRole) {
        //1.更新角色自身信息
        int rows=sysRoleDao.updateRole(sysRole);
        if(rows==0)throw new ServiceException("记录可能已经不存在");
        //2.更新角色菜单关系数据
        //2.1删除原有关系
        sysRoleMenuDao.deleteByRoleId(sysRole.getId());
        //2.2添加新的关系
        sysRoleMenuDao.insertRoleMenus(sysRole.getId(),
                sysRole.getMenuIds());
        return rows;
    }
    @Transactional(readOnly = true)
    @Override
    public List<CheckBox> findCheckRoles() {
        return sysRoleDao.selectCheckRoles();
    }

}
